package com.cloud.wms.ui.in.fragment;

import android.app.DatePickerDialog;
import android.os.Bundle;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.CheckedTextView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.cloud.core.utils.DateUtil;
import com.cloud.core.utils.NumberUtils;
import com.cloud.core.utils.TimeUtils;
import com.cloud.widget.ScanText;
import com.cloud.wms.R;
import com.cloud.wms.base.BaseViewPagerFragment;
import com.cloud.wms.tools.DatePickerUtils;
import com.cloud.wms.ui.in.contract.InInventoryContract;
import com.cloud.wms.ui.in.entity.InCommodityEntity;
import com.cloud.wms.ui.in.entity.InOrderEntity;
import com.cloud.wms.ui.in.presnter.InInventoryPresenter;
import com.cloud.wms.ui.main.entity.TaskEntity;
import com.cloud.wms.widget.dialog.TaskCompleteDialog;
import com.trello.rxlifecycle3.LifecycleTransformer;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @Author:Chen
 * @Date: 2021-01-24 16:59
 * @Description:
 */
public class HaveMarkFragment extends BaseViewPagerFragment<InInventoryPresenter> implements InInventoryContract.View {
    @BindView(R.id.scan_text)
    ScanText scanText;
    @BindView(R.id.btn_good)
    CheckedTextView btnGood;
    @BindView(R.id.btn_bad)
    CheckedTextView btnBad;
    @BindView(R.id.tv_member_name)
    TextView tvMemberName;
    @BindView(R.id.iv_member_name)
    ImageView ivMemberName;
    @BindView(R.id.tv_commodity_code)
    TextView tvCommodityCode;
    @BindView(R.id.tv_commodity_name)
    TextView tvCommodityName;
    @BindView(R.id.tv_produce_date)
    TextView tvProduceDate;
    @BindView(R.id.iv_produce_date)
    ImageView ivProduceDate;
    @BindView(R.id.tv_deadline_date)
    TextView tvDeadlineDate;
    @BindView(R.id.iv_deadline_date)
    ImageView ivDeadlineDate;
    @BindView(R.id.tv_in_date)
    TextView tvInDate;
    @BindView(R.id.iv_in_date)
    ImageView ivInDate;
    @BindView(R.id.et_mark_flag)
    EditText etMarkFlag;
    @BindView(R.id.et_mark_size)
    EditText etMarkSize;
    @BindView(R.id.et_mark_amount)
    EditText etMarkAmount;
    @BindView(R.id.tv_commodity_amount)
    TextView tvCommodityAmount;
    @BindView(R.id.rg_mark_print)
    RadioGroup rgMarkPrint;
    @BindView(R.id.btn_submit)
    TextView btnSubmit;
    private TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            verifyRequired();
            tvCommodityAmount.setText(NumberUtils.bigMultiply(etMarkAmount.getText().toString().trim(), etMarkSize.getText().toString().trim()));
        }
    };
    private boolean isPrint = true;
    private InOrderEntity inOrder;
    private InCommodityEntity commodityEntity;
    private DatePickerDialog mDateDialog;
    private TaskEntity taskEntity;
    private String beginTime;

    @Override
    protected int getResId() {
        return R.layout.fragment_in_inventory_have_mark;
    }

    @Override
    protected void setupComponent() {
        getFragmentComponent().inject(this);
    }

    @Override
    protected void initEvent(Bundle bundle) {
        beginTime = TimeUtils.getCurrentDateAndTime();
        inOrder = getArguments().getParcelable("InOrder");
        taskEntity = getArguments().getParcelable("Task");
        if (inOrder != null)
            tvMemberName.setText(inOrder.getMemberName());
        else
            tvMemberName.setText(taskEntity.getMemberName());
        btnSubmit.setEnabled(false);
        btnGood.setChecked(true);
        tvCommodityAmount.setText("0");
        etMarkAmount.addTextChangedListener(textWatcher);
        etMarkSize.addTextChangedListener(textWatcher);

        rgMarkPrint.setOnCheckedChangeListener((group, checkedId) -> {
            isPrint = checkedId == R.id.rb_mark_print;
        });

        tvInDate.setText(DateUtil.format_yyyy_MM_dd(System.currentTimeMillis()));
    }

    @Override
    public ScanText getScanText() {
        return scanText;
    }

    @Override
    protected void onScanHandle(String result, int resultCode) {
        super.onScanHandle(result, resultCode);
        scanText.addHistory(result);
        mPresenter.checkCommodityCode(inOrder != null ? String.valueOf(inOrder.getInID()) : taskEntity.getMainBillID() + "", result);
    }

    @Override
    protected void initData() {

    }

    private void verifyRequired() {
        if (commodityEntity == null) {
            btnSubmit.setEnabled(false);
            return;
        }
        String markSize = etMarkSize.getText().toString().trim();
        if (TextUtils.isEmpty(markSize)) {
            btnSubmit.setEnabled(false);
            return;
        }
        String markAmount = etMarkAmount.getText().toString().trim();
        if (TextUtils.isEmpty(markAmount)) {
            btnSubmit.setEnabled(false);
            return;
        }
        String produceDate = tvProduceDate.getText().toString().trim();
        if (TextUtils.isEmpty(produceDate)) {
            btnSubmit.setEnabled(false);
            return;
        }
        String deadlineDate = tvDeadlineDate.getText().toString().trim();
        if (TextUtils.isEmpty(deadlineDate)) {
            btnSubmit.setEnabled(false);
            return;
        }
        String inDate = tvInDate.getText().toString().trim();
        if (TextUtils.isEmpty(inDate)) {
            btnSubmit.setEnabled(false);
            return;
        }
        btnSubmit.setEnabled(true);
    }

    private void dateSelector(TextView textView, boolean isTodayAfter) {
        mDateDialog = DatePickerUtils.datePicker(getContext(),
                isTodayAfter,
                (view, year, month, dayOfMonth) -> {
                    String date = DateUtil.formatYMD(year, month + 1, dayOfMonth);
                    textView.setText(date);
                    verifyRequired();
                });
        mDateDialog.show();
    }

    private void verifySubmit() {
        if (commodityEntity == null) {
            info("请先扫描商品");
            return;
        }
        String produceDate = tvProduceDate.getText().toString().trim();
        if (TextUtils.isEmpty(produceDate)) {
            info("生产日期为必填项");
            return;
        }
        String deadlineDate = tvDeadlineDate.getText().toString().trim();
        if (TextUtils.isEmpty(deadlineDate)) {
            info("截止日期为必填项");
            return;
        }
        String inDate = tvInDate.getText().toString().trim();
        if (TextUtils.isEmpty(inDate)) {
            info("入库时间为必填项");
            return;
        }
        String markSize = etMarkSize.getText().toString().trim();
        if (TextUtils.isEmpty(markSize)) {
            info("箱唛规格为必填项");
            return;
        }
        if (!NumberUtils.isInt(markSize) || NumberUtils.getIntegerValue(markSize) <= 0) {
            info("箱唛规格必须为整数且必须大于0");
            return;
        }
        String markAmount = etMarkAmount.getText().toString().trim();
        if (TextUtils.isEmpty(markAmount)) {
            info("箱唛箱数为必填项");
            return;
        }
        if (!NumberUtils.isInt(markAmount) || NumberUtils.getIntegerValue(markAmount) <= 0) {
            info("箱唛箱数必须为整数且必须大于0");
            return;
        }

        int commodityType = 1;
        if (btnBad.isChecked()) commodityType = 2;
        String markFlag = etMarkFlag.getText().toString().trim();

        mPresenter.submitMarkInventory(
                taskEntity,
                inOrder,
                commodityEntity.getCommodityId(),
                commodityType,
                produceDate,
                deadlineDate,
                inDate,
                markFlag,
                markSize,
                markAmount,
                isPrint, beginTime);
    }

    @Override
    public void onSuccess(Message message) {
        switch (message.what) {
            case InInventoryPresenter.IN_CHECK_CODE:
                commodityEntity = (InCommodityEntity) message.obj;
                tvCommodityName.setText(commodityEntity.getCommodityName());
                tvCommodityCode.setText(commodityEntity.getBarCode());
                break;
            case InInventoryPresenter.IN_MARK_SUBMIT:
                success("清点提交成功!");
                resetView();
                mPresenter.loadInCommodityList(inOrder != null ? String.valueOf(inOrder.getInID()) : taskEntity.getMainBillID() + "", false);
                break;
            case InInventoryPresenter.CHECK_COMPLETE:
                new TaskCompleteDialog(getActivity()).show();
                break;
        }
    }

    private void resetView() {
        commodityEntity = null;
        btnSubmit.setEnabled(false);
        btnGood.setChecked(true);
        btnBad.setChecked(false);
        tvInDate.setText(DateUtil.format_yyyy_MM_dd(System.currentTimeMillis()));
        tvCommodityCode.setText("");
        tvCommodityName.setText("");
        tvDeadlineDate.setText("");
        tvProduceDate.setText("");
        etMarkAmount.setText("");
        etMarkFlag.setText("");
        etMarkSize.setText("");
        tvCommodityAmount.setText("0");
    }

    @OnClick({R.id.btn_good, R.id.btn_bad, R.id.tv_produce_date, R.id.iv_produce_date, R.id.tv_deadline_date, R.id.iv_deadline_date, R.id.tv_in_date, R.id.iv_in_date, R.id.btn_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_good:
                btnGood.setChecked(true);
                btnBad.setChecked(false);
                switchCommodityType();
                break;
            case R.id.btn_bad:
                btnGood.setChecked(false);
                btnBad.setChecked(true);
                switchCommodityType();
                break;
            case R.id.tv_produce_date:
            case R.id.iv_produce_date:
                dateSelector(tvProduceDate, false);
                break;
            case R.id.tv_deadline_date:
            case R.id.iv_deadline_date:
                dateSelector(tvDeadlineDate, true);
                break;
            case R.id.tv_in_date:
            case R.id.iv_in_date:
                dateSelector(tvInDate, true);
                break;
            case R.id.btn_submit:
                verifySubmit();
                break;
        }
    }

    private void switchCommodityType() {
        if (commodityEntity != null) {
            int commodityType = 1;
            if (btnBad.isChecked()) commodityType = 2;
            commodityEntity.setStockType(commodityType);
        }
    }

    @Override
    public <R> LifecycleTransformer<R> toLifecycle() {
        return bindToLifecycle();
    }

    public static BaseViewPagerFragment newInstance(Bundle bundle) {
        HaveMarkFragment fragment = new HaveMarkFragment();
        fragment.setArguments(bundle);
        return fragment;
    }
}
